<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\User;
use App\Models\WeChatUser;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Laravel\Socialite\Facades\Socialite;

class LoginController extends Controller
{
    public function getWxAuthUrl(Request $request)
    {
        $state = $request->get('state') ?? '1';

        $request->session()->put('state', $state);

        return response()->json([
            'code'    => 1,
            'message' => 'success',
            'result'  => [
                'url' => Socialite::driver('wechat')->redirectUrl($request->get('redirectUrl'))->getAuthUrl($state),
            ],
        ]);
    }

    public function getUserInfoByWxMpCode(Request $request)
    {
        $state = $request->get('state') ?? '1';

        $request->session()->put('state', $state);

        $user = Socialite::driver('wechat')->user();

        $userInfo = $user->user;

        /** @var WeChatUser $weChatUser */
        $weChatUser = WeChatUser::query()->firstOrNew([
            'openid' => $user->getId()
        ], [
            'nickname' => $user->getNickname(),
            'sex'      => $userInfo['sex'] ?? 0,
            'language' => $userInfo['language'] ?? '',
            'city'     => $userInfo['city'] ?? '',
            'province' => $userInfo['province'] ?? '',
            'country'  => $userInfo['country'] ?? '',
            'avatar'   => $user->getAvatar(),
        ]);

        if ($weChatUser->user_id) {
            // 登录已绑定用户
            $userModel = User::query()->find($weChatUser->user_id);

            if (! $userModel) {
                return response()->json([
                    'code' => -1,
                    'msg'  => '找不到用户',
                ]);
            }
        } else {
            // 创建新用户
            $username = $user->getNickname() . Str::random(6);

            /** @var User $userModel */
            $userModel = User::query()->create([
                'name'     => $user->getNickname() ?? $username,
                'username' => $username,
                'email'    => $username . '@example.org',
                'password' => '',
            ]);

            // 绑定新用户
            $weChatUser->user_id = $userModel->id;

            $weChatUser->save();
        }

        return response()->json([
            'code'    => 1,
            'message' => 'success',
            'result'  => array_merge($userInfo, [
                'user_cert'        => $userModel->id,
                'user_cert_expire' => 86400 * 15,
            ]),
        ]);
    }
}
